<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <script src="https://unpkg.com/axios@0.24.0/dist/axios.min.js"></script>
</head>

<body>
  <input id="fileInput" type="file" />
  <script>
    import SparkMD5 from 'spark-md5';

    const fileInput = document.querySelector('#fileInput');
    const chunkSize = 5 * 1024 * 1024 * 1024;

    /* 通过 md5 加密文件 buffer 来生成唯一 hash 值  */
    const getFileHash = async (file) => {
      return new Promise((resolve, reject) => {
        const fileReader = new FileReader();
        fileReader.onload = (e) => {
          const fileHash = SparkMD5.ArrayBuffer.hash(e.target.result);
          resolve(fileHash);
        }
        fileReader.onerror = (e) => {
          reject('文件读取失败', e);
        }
        fileReader.readAsArrayBuffer(file);
      })
    }

    fileInput.onchange = async function () {
      const file = fileInput.files[0];
      const chunks = [];
      let startPos = 0;
      while (startPos < file.size) {
        chunks.push(file.slice(startPos, startPos + chunkSize));
        startPos += chunkSize;
      }

      const hash = getFileHash(file)

      const tasks = [];
      chunks.map((chunk, index) => {
        const data = new FormData();

        data.set('name', hash + '_' + file.name + '-' + index)
        data.set('hash', hash)
        data.append('files', chunk);
        tasks.push(axios.post('http://localhost:3000/upload', data, {
          onUploadProgress: (progressEvent) => {
            console.log('上传进度：', (progressEvent.loaded / progressEvent.total * 100).toFixed(2) + '%');
          }
        }));
      })
      await Promise.all(tasks);
      axios.get('http://localhost:3000/merge?name=' + randomStr + '_' + file.name);
    }

  </script>
</body>

</html>